import ctypes
import os
import platform
import subprocess
import sys

windows = "Windows"
linux = "Linux"


def is_admin():
    try:
        return ctypes.windll.shell32.IsUserAnAdmin()
    except:
        return False


def exe_command(command):
    if type(command) is list:
        if is_windows():
            final_command = " && ".join(command)
        else:
            final_command = command
    else:
        final_command = command
    p = subprocess.Popen(final_command, stdin=None, stdout=sys.stdout, stderr=sys.stderr,
                         shell=True)
    p.communicate()
    return p.returncode
    # print(stdout.decode(encoding=("gbk" if is_windows() else "utf8")))
    # print(out_info.decode('gbk'))
    # print(error_info.decode('gbk'))


def exe_command_with_powershell(command: str):
    return subprocess.run(["powershell", "-Command", command], capture_output=True, text=True)


def exe_file_with_powershell(file_path: str):
    return subprocess.run(["powershell", "-File", file_path], capture_output=True, text=True)


def exe_command_result(command):
    if type(command) is list:
        if is_windows():
            final_command = " && ".join(command)
        else:
            final_command = command
    else:
        final_command = command
    return subprocess.run(final_command, capture_output=True, text=True, shell=True)


# 设置当前路径
def set_path():
    path = os.getcwd()
    exe_command('cd ' + path)


# 获取命令包含路径
def get_command_include_path(command):
    path = 'cd ' + os.getcwd()
    commands = [path, command]
    return " && ".join(commands)


# 打开文件
def startfile(filename):
    try:
        os.startfile(filename)
    except FileNotFoundError as e:
        print(f"An error occurred: {e}")


# 获取系统
def get_system():
    return platform.system()


# 判断系统是否为windows
def is_windows():
    return get_system() == windows


# 判断系统是否为linux
def is_linux():
    return get_system() == linux


# 获取命令所在路径
def get_command_path():
    return sys.path[0] + os.sep


# 包含命令所在路径
def include_command_path(path):
    if path.startswith(os.sep):
        return sys.path[0] + path
    else:
        return get_command_path() + path
